/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.web.frontendproject.zerocode.operation;

import com.inspur.edp.lcm.metadata.api.IMetadataContent;
import com.inspur.edp.web.common.environment.ExecuteEnvironment;
import com.inspur.edp.web.formmetadata.metadata.formdom.FormDOM;
import com.inspur.edp.web.formmetadata.metadatamanager.StateMachineMetadataManager;
import com.inspur.edp.web.jitruntimebuild.api.entity.JitMetadataTypeEnum;
import com.inspur.edp.web.frontendproject.zerocode.ZeroCodeFormParameter;
import com.inspur.edp.web.frontendproject.zerocode.ZeroCodeFormRefMetadataParameter;

import java.util.HashMap;

public class StateMachineMetadataOperation {
    /**
     * 保存
     *
     * @param formParameter
     */
    public void save(FormDOM json, ZeroCodeFormParameter formParameter,String wevDevPath,String formMetadataFileName) {
        if (json.getModule() != null && json.getModule().getStateMachines() != null && json.getModule().getStateMachines().size() > 0) {
            StateMachineMetadataManager smManager = new StateMachineMetadataManager(ExecuteEnvironment.Design, false);
            StringBuilder stateMachines = new StringBuilder();
            stateMachines.append("{");
            int index = 0;
            for (HashMap<String, Object> o : json.getModule().getStateMachines()) {
                if (index > 0) {
                    stateMachines.append(",");
                }
                String uri = o.get("uri").toString();

                ZeroCodeFormRefMetadataParameter formRefMetadataParameter = formParameter.getSpecialFormRefMetaData(uri, JitMetadataTypeEnum.StateMachine);
                if (formRefMetadataParameter != null) {
                    IMetadataContent obj = formRefMetadataParameter.getMetadata().getContent();
                    String sm_json = smManager.serialize(obj);
                    String idStr = o.get("id").toString();
                    stateMachines.append("\"").append(idStr).append("\":");
                    stateMachines.append(sm_json);
                    index += 1;
                }

            }
            stateMachines.append("}");

            // Save StateMachine
            smManager.saveMetadataFile(wevDevPath, String.format("%1$s.sm.json", formMetadataFileName.toLowerCase()), stateMachines.toString());
        }
    }


}
